package com.zgx.plus.common.api.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.zgx.plus.common.api.model.SysOperLogEntity;
import com.zgx.plus.common.constant.ServiceNameConstants;
import com.zgx.plus.common.response.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.RequestEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

/**
 * 异步调用日志服务
 */
@Service
public class AsyncLogService {

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 保存系统日志记录 @See TokenService
     */
    @Async("threadPoolTaskExecutor")
    public void saveSysLog(SysOperLogEntity sysOperLog, Object token) {

        URI uri = UriComponentsBuilder.fromHttpUrl(ServiceNameConstants.SYSTEM_SERVICE).path("/operlog").build(true).toUri();
        RequestEntity<String> requestEntity = RequestEntity.post(uri).
                header("Authorization", StrUtil.concat(true, "Bearer ", String.valueOf(token))).
                accept(MediaType.APPLICATION_JSON).contentType(MediaType.APPLICATION_JSON).
                body(JSON.toJSONString(sysOperLog));
        System.out.println("==>" + JSON.toJSONString(sysOperLog));
        restTemplate.exchange(requestEntity, R.class);
    }
}
